/**
 * This file is part of Too-OneBee.
 *
 * Too-OneBee is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Too-OneBee is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Too-OneBee.  If not, see <http://www.gnu.org/licenses/>.
 */
package net.dataforte.tooonebee.jndi;

import static net.dataforte.tooonebee.Menu.menu;

import java.io.PrintWriter;
import java.util.Set;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dataforte.tooonebee.Menu;
import net.dataforte.tooonebee.ServiceIntrospector;

public class JNDIIntrospector extends ServiceIntrospector {

	@Override
	public String getRequestPath() {
		return "jndi";
	}
	
	@Override
	public Set<Menu> getMenuEntries() {
		Set<Menu> entries = super.getMenuEntries();
		entries.add(
			menu("JNDI", this.getRequestPath())
		);
		return entries;
	}

	@Override
	public void handleRequest(HttpServlet servlet, HttpServletRequest req, HttpServletResponse res) throws Exception {
		res.setContentType("text/xml; UTF-8");
		PrintWriter writer = res.getWriter();
		writer.println("<root>");
		traverseContext(writer, new InitialContext());
		traverseContext(writer, (Context) new InitialContext().lookup("java:comp/env"));
		writer.println("</root>");
	}

	private void traverseContext(PrintWriter out, Context ctx) throws Exception {
		NamingEnumeration<NameClassPair> ne = ctx.list("");
		if (ne.hasMoreElements()) {
			while (ne.hasMoreElements()) {
				NameClassPair ncp = (NameClassPair) ne.nextElement();
				out.printf("<item name=\"%s\" class=\"%s\">", ncp.getName(), ncp.getClassName());
				try {
					Object object = ctx.lookup(ncp.getName());
					if (object instanceof Context) {
						traverseContext(out, (Context) object);
					}
				} catch (Throwable t) {
					// Ignora
				}
				out.print("</item>");

			}
		}
	}
}
